package com.lsb.utils;


import com.lsb.response.Result;
import com.tencentcloudapi.captcha.v20190722.CaptchaClient;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultRequest;
import com.tencentcloudapi.captcha.v20190722.models.DescribeCaptchaResultResponse;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;


//腾讯验证码校验
public class TencentCaptchaUtils {

    public static Result authenticationCaptcha(String secretId, String secretKey,
                                             Long captchaAppId, String appSecretKey,
                                            String ticket , String randStr) {
        try{
            Credential credential = new Credential( secretId , secretKey ) ;
            //调用API验证
            HttpProfile httpProfile = new HttpProfile( ) ;
            httpProfile.setEndpoint( "captcha.tencentcloudapi.com" ) ;
            ClientProfile clientProfile = new ClientProfile( ) ;
            clientProfile.setHttpProfile( httpProfile ) ;
            CaptchaClient client = new CaptchaClient( credential , "" , clientProfile ) ;
            DescribeCaptchaResultRequest req = new DescribeCaptchaResultRequest( ) ;
            req.setCaptchaType( 9L ) ;
            req.setTicket( ticket ) ;
            req.setRandstr( randStr );
            req.setUserIp("127.0.0.1") ;
            req.setAppSecretKey( appSecretKey ) ;
            req.setCaptchaAppId( captchaAppId ) ;
            DescribeCaptchaResultResponse response = client.DescribeCaptchaResult( req ) ;
            //返回校验的code和message,下面列举官方文档中的部分常见code
            //1 OK 验证通过
            //6 user code len error 验证码长度不匹配，请检查请求是否带Randstr参数，Randstr参数大小写是否有误
            //7 captcha no match 验证码答案不匹配/Randstr参数不匹配，请重新生成Randstr、Ticket进行校验
            //15 decrypt fail 验证码签名解密失败，票据校验失败，请检查Ticket票据是否与前端返回Ticket一致
            Result result = Result.ok().data("code",response.getCaptchaCode().intValue()).message(response.getCaptchaMsg());
            return result;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace( ) ;
            return Result.error().message("出现异常了!");
        }
    }
}
